package model.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

public class WordManagerDAO {
	

	/**
	 * Thêm một từ vào danh sách từ điển
	 * @param langSource
	 * @param langTarget
	 * @param word
	 * @param meaning
	 * @param img
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 */
	public void AddWord(String langSource, String langTarget, String word,
			String meaning, String img) throws ParserConfigurationException,
			SAXException, IOException {
		
		String xmlFilePath = "F:\\Eclipse_Project\\MathDict\\WebContent\\Dictionary\\"
				+ langSource + "" + langTarget + ".xml";
		String wordAfter = WordAfter(langSource, langTarget, word);
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = factory.newDocumentBuilder();
			
			InputStream inputStream= new FileInputStream(xmlFilePath);
			InputStreamReader inputReader = new InputStreamReader(inputStream,"UTF-8");
			InputSource inputSource = new InputSource(inputReader);
			inputSource.setEncoding("UTF-8");

			Document doc = docBuilder.parse(inputSource);
			Text wordNew = doc.createTextNode(word);
			Text mean = doc.createTextNode(meaning);
			Text imgNew = doc.createTextNode(img);
			
			Element wordElement = doc.createElement("words");
			// Creat new word and meaning
			Element w = doc.createElement("word");
			w.appendChild(wordNew);
			Element m = doc.createElement("mean");
			m.appendChild(mean);
			Element im = doc.createElement("img");
			im.appendChild(imgNew);
			// Add new word into <words> node
			wordElement.appendChild(w);
			wordElement.appendChild(m);
			wordElement.appendChild(im);
			
			// Starting parser
			NodeList list = doc.getElementsByTagName("words");
			boolean check = false;
			// Look through all the <words> node
			for (int i = 0; i < list.getLength(); i++) {
				// Get Node
				Node node = (Node) list.item(i);
				Node nNode0 = list.item(0);
				Element eElement0 = (Element) nNode0;
				String temp = eElement0.getElementsByTagName("word").item(0).getTextContent();
				if (wordAfter == null){
					node.getParentNode().appendChild(wordElement);
					check = true;
				}else
				if (wordAfter.equals(temp)) {
					node.getParentNode().insertBefore(wordElement, nNode0);
					check = true;
				}
					else {
					// Look through entire settings file
					NodeList childList = node.getChildNodes();
					// Look through all the children
					for (int x = 1; x < childList.getLength(); x++) {
						Node child = (Node) childList.item(x);
						// Only the JOB children will be looked in.
						if (child.getNodeType() == Node.ELEMENT_NODE
								&& child.getNodeName().equalsIgnoreCase("word")
								&& child.getTextContent().equalsIgnoreCase(
										wordAfter)) {

							node.getParentNode().insertBefore(wordElement, list.item(i));
							check = true;
							if (check) {
								break;
							}
						}
					}
					if (check) {
						break;
					}
				}
			}
			try {
				OutputStream output = new FileOutputStream(xmlFilePath);
				OutputStreamWriter outputWriter = new OutputStreamWriter(output, "UTF-8");
				
				OutputFormat format = new OutputFormat(doc);
				XMLSerializer serial = new XMLSerializer(outputWriter, format);
				serial.asDOMSerializer();
				serial.serialize(doc.getDocumentElement());
				outputWriter.flush();
				outputWriter.close();
			} catch (IOException io) {
				io.printStackTrace();
			}
		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (SAXException saxe) {
			saxe.printStackTrace();
		}
	}
	
    
	/**
	 * Xóa một từ ra khỏi danh sách từ điển
	 * @param langSource
	 * @param langTarget
	 * @param word
	 */
	public void RemoveWord(String langSource, String langTarget, String word) {
		
		String xmlFilePath = "F:\\Eclipse_Project\\MathDict\\WebContent\\Dictionary\\"
				+ langSource + "" + langTarget + ".xml";
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = factory.newDocumentBuilder();
			
			InputStream inputStream= new FileInputStream(xmlFilePath);
			InputStreamReader inputReader = new InputStreamReader(inputStream,"UTF-8");
			InputSource inputSource = new InputSource(inputReader);
			inputSource.setEncoding("UTF-8");

			Document doc = docBuilder.parse(inputSource);

			// Starting parser
			NodeList list = doc.getElementsByTagName("words");
			for (int i = 0; i < list.getLength(); i++) {
				// Get Node
				Node node = (Node) list.item(i);
				// Look through entire settings file
				NodeList childList = node.getChildNodes();
				// Look through all the children
				for (int x = 0; x < childList.getLength(); x++) {
					Node child = (Node) childList.item(x);
					// Only the JOB children will be looked in.
					if (child.getNodeType() == Node.ELEMENT_NODE
							&& child.getNodeName().equalsIgnoreCase("word")
							&& child.getTextContent().equalsIgnoreCase(word)) {
						// Delete job node here
						node.getParentNode().removeChild(node);
					}
				}
			}
			try {
				OutputStream output = new FileOutputStream(xmlFilePath);
				OutputStreamWriter outputWriter = new OutputStreamWriter(output, "UTF-8");
				
				OutputFormat format = new OutputFormat(doc);
				XMLSerializer serial = new XMLSerializer(outputWriter, format);
				serial.asDOMSerializer();
				serial.serialize(doc.getDocumentElement());
				outputWriter.flush();
				outputWriter.close();
			} catch (IOException io) {
				io.printStackTrace();
			}
		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (SAXException saxe) {
			saxe.printStackTrace();
		}
	}
	
	
	/**
	 * Sửa nội dung từ trong danh sách từ điển
	 * @param langSource
	 * @param langTarget
	 * @param word
	 * @param meaning
	 */
	public void EditWord(String langSource, String langTarget, String word, String meaning) {
		
		String xmlFilePath = "F:\\Eclipse_Project\\MathDict\\WebContent\\Dictionary\\"
				+ langSource + "" + langTarget + ".xml";
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = factory.newDocumentBuilder();
			
			InputStream inputStream= new FileInputStream(xmlFilePath);
			InputStreamReader inputReader = new InputStreamReader(inputStream,"UTF-8");
			InputSource inputSource = new InputSource(inputReader);
			inputSource.setEncoding("UTF-8");

			Document doc = docBuilder.parse(inputSource);

			// Starting parser
			NodeList list = doc.getElementsByTagName("words");
			for (int i = 0; i < list.getLength(); i++) {
				// Get Node
				Node node = (Node) list.item(i);
				// Look through entire settings file
				NodeList childList = node.getChildNodes();
				// Look through all the children
				for (int x = 0; x < childList.getLength(); x++) {
					Node child = (Node) childList.item(x);
					// Only the JOB children will be looked in.
					if (child.getNodeType() == Node.ELEMENT_NODE
							&& child.getNodeName().equalsIgnoreCase("word")
							&& child.getTextContent().equalsIgnoreCase(word)) {
						Text mean = doc.createTextNode(meaning);
						Element newMean = doc.createElement("mean");
						newMean.appendChild(mean);
						// Edit meaning
						child.getParentNode().replaceChild(newMean, childList.item(x+1));
					}
				}
			}
			try {
				OutputStream output = new FileOutputStream(xmlFilePath);
				OutputStreamWriter outputWriter = new OutputStreamWriter(output, "UTF-8");
				
				OutputFormat format = new OutputFormat(doc);
				XMLSerializer serial = new XMLSerializer(outputWriter, format);
				serial.asDOMSerializer();
				serial.serialize(doc.getDocumentElement());
				outputWriter.flush();
				outputWriter.close();
			} catch (IOException io) {
				io.printStackTrace();
			}
		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (SAXException saxe) {
			saxe.printStackTrace();
		}
	}
	
	/**
	 * Trả về vị trí từ đứng sau từ ta có theo thứ tự alphabet
	 * @param langSource
	 * @param langTarget
	 * @param word
	 * @return
	 */
	public String WordAfter(String langSource, String langTarget, String word){
		String xmlFilePath = "F:\\Eclipse_Project\\MathDict\\WebContent\\Dictionary\\"+langSource+""+langTarget+".xml";
		String temp1;
		String temp2;
		String result = null;
		boolean check = false;
        try {
            File xmlFile = new File(xmlFilePath);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(xmlFile);
            doc.getDocumentElement().normalize();
            NodeList nList = doc.getElementsByTagName("words");
            
            Node nNode0 = nList.item(0);
            Element eElement0 = (Element) nNode0;
            String temp = eElement0.getElementsByTagName("word").item(0).getTextContent();
            if(word.compareTo(temp)<0){
            	result = temp;
            	check = true;
            }
            else{
            for (int i = 0; i < nList.getLength(); i++) {
                Node nNode1 = nList.item(i);
                if(i<nList.getLength()-1){
                	Node nNode2 = nList.item(i+1);
                	 if (nNode1.getNodeType() == Node.ELEMENT_NODE) {
                         Element eElement1 = (Element) nNode1;
                         Element eElement2 = (Element) nNode2;
                         temp1 = eElement1.getElementsByTagName("word").item(0).getTextContent();
                         temp2 = eElement2.getElementsByTagName("word").item(0).getTextContent();
                         if(word.compareTo(temp1) > 0 && word.compareTo(temp2)<0){
                         	result = temp2;
                         	check = true;
                         }
                     }
                }
                
                if(check) break;
            }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
		return result;
	}
}
